package com.nari.ncps.screen.service.impl.al;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.PadEnvInfo;
import com.nari.ncps.screen.entity.al.AlOpermonEnergyCon;
import com.nari.ncps.screen.entity.al.AlSafetyenvAlarm;
import com.nari.ncps.screen.entity.coal.CoalProdoperOsv;
import com.nari.ncps.screen.mapper.al.AlOpermonEnergyConMapper;
import com.nari.ncps.screen.mapper.al.AlSafetyenvAlarmMapper;
import com.nari.ncps.screen.service.al.AlSafetyenvAlarmService;
import com.nari.ncps.screen.vo.al.AlOpermonEnergyConVO;
import com.nari.ncps.screen.vo.al.AlOpermonEnergyConsumptionVO;
import com.nari.ncps.screen.vo.al.AlSafetyenvEnvIndicatorsVO;
import com.nari.ncps.screen.vo.al.AluminumSafetyEnvVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * <p>
 * 环保指标预警表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Slf4j
@Service
public class AlSafetyenvAlarmServiceImpl extends ServiceImpl<AlSafetyenvAlarmMapper, AlSafetyenvAlarm> implements AlSafetyenvAlarmService {

    @Autowired
    private AlOpermonEnergyConMapper alOpermonEnergyConMapper;
    @Override
    public List<AlOpermonEnergyConsumptionVO> getEnergyConsumptionData() {
        log.info("开始查询能源消费监测数据");
        
        // 使用MyBatis Plus查询最新的10条环保指标数据
        QueryWrapper<AlSafetyenvAlarm> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("year", "month", "day")
                .last("LIMIT 10");
        
        List<AlSafetyenvAlarm> alarmList = this.list(queryWrapper);
        log.info("从数据库查询到{}条记录", alarmList == null ? 0 : alarmList.size());
        
        // 如果数据库中没有数据，返回mock数据
        if (alarmList == null || alarmList.isEmpty()) {
            log.info("数据库无数据，返回mock数据");
            return generateMockEnergyConsumptionData();
        }
        
        // 检查是否有有效数据
        boolean hasValidData = false;
        for (AlSafetyenvAlarm alarm : alarmList) {
            if (alarm.getPmRealValue() != null || alarm.getSo2RealValue() != null || 
                alarm.getFluorideRealValue() != null) {
                hasValidData = true;
                break;
            }
        }
        
        if (!hasValidData) {
            log.info("数据库有记录但无有效数据，返回mock数据");
            return generateMockEnergyConsumptionData();
        }
        
        // 转换为VO对象列表
        List<AlOpermonEnergyConsumptionVO> voList = new ArrayList<>();
        for (AlSafetyenvAlarm alarm : alarmList) {
            AlOpermonEnergyConsumptionVO vo = new AlOpermonEnergyConsumptionVO();
            vo.setPmRealValue(alarm.getPmRealValue());
            vo.setPmStandardValue(alarm.getPmStandardValue());
            vo.setSo2RealValue(alarm.getSo2RealValue());
            vo.setSo2StandardValue(alarm.getSo2StandardValue());
            vo.setFluorideRealValue(alarm.getFluorideRealValue());
            vo.setFluorideStandardValue(alarm.getFluorideStandardValue());
            vo.setUnitCode(alarm.getOrgCode());
            vo.setUnitName(alarm.getOrgName());
            voList.add(vo);
        }
        
        log.info("返回{}条能源消费监测数据", voList.size());
        return voList;
    }


    @Override
    public List<AlOpermonEnergyConVO> getEnergyConData() {
        log.info("开始查询能源消费监测数据");
        Calendar calendar = Calendar.getInstance();
        int currentYear = calendar.get(Calendar.YEAR);

        LambdaQueryWrapper<AlOpermonEnergyCon> alOpermonEnergyConQuery = new LambdaQueryWrapper<>();
        alOpermonEnergyConQuery.ge(AlOpermonEnergyCon::getYear, currentYear-1);
        List<AlOpermonEnergyCon> alOpermonEnergyConList = alOpermonEnergyConMapper.selectList(alOpermonEnergyConQuery);
        // 转换为VO对象列表
        List<AlOpermonEnergyConVO> voList = new ArrayList<>();
        for (AlOpermonEnergyCon list : alOpermonEnergyConList) {
            AlOpermonEnergyConVO vo = new AlOpermonEnergyConVO();
            vo.setYear(list.getYear());
            vo.setCurrentYearEnergy(list.getCurrentYearEnergy());
            vo.setLastYearEnergy(list.getLastYearEnergy());
            vo.setEnergyYoyRate(list.getEnergyYoyRate());

            voList.add(vo);
        }

        log.info("返回{}条能源消费监测数据", voList.size());
        return voList;
    }


    
    /**
     * 生成mock能源消费监测数据
     * 覆盖三个铝厂的环保指标数据
     */
    private List<AlOpermonEnergyConsumptionVO> generateMockEnergyConsumptionData() {
        log.info("生成mock能源消费监测数据");
        List<AlOpermonEnergyConsumptionVO> mockList = new ArrayList<>();
        
        // 铝厂信息
        String[][] plants = {
            {"HMHL001", "霍煤鸿铝厂"},
            {"ZHENR001", "扎哈淖尔铝厂"},
            {"BYHL001", "白音华铝厂"}
        };
        
        // 为每个铝厂生成多条监测数据
        for (int i = 0; i < 10; i++) {
            String[] plant = plants[i % 3];
            AlOpermonEnergyConsumptionVO vo = new AlOpermonEnergyConsumptionVO();
            vo.setUnitCode(plant[0]);
            vo.setUnitName(plant[1]);
            
            // 颗粒物数据 (标准值通常为10-30 mg/m³)
            BigDecimal pmStandard = BigDecimal.valueOf(20.00);
            BigDecimal pmReal = BigDecimal.valueOf(12.0 + (i % 5) * 1.5 + (i % 3) * 0.8)
                    .setScale(2, RoundingMode.HALF_UP);
            vo.setPmStandardValue(pmStandard);
            vo.setPmRealValue(pmReal);
            
            // 二氧化硫数据 (标准值通常为100-200 mg/m³)
            BigDecimal so2Standard = BigDecimal.valueOf(150.00);
            BigDecimal so2Real = BigDecimal.valueOf(85.0 + (i % 4) * 8.5 + (i % 3) * 5.2)
                    .setScale(2, RoundingMode.HALF_UP);
            vo.setSo2StandardValue(so2Standard);
            vo.setSo2RealValue(so2Real);
            
            // 氟化物数据 (标准值通常为3-5 mg/m³)
            BigDecimal fluorideStandard = BigDecimal.valueOf(3.00);
            BigDecimal fluorideReal = BigDecimal.valueOf(1.5 + (i % 5) * 0.25 + (i % 2) * 0.15)
                    .setScale(2, RoundingMode.HALF_UP);
            vo.setFluorideStandardValue(fluorideStandard);
            vo.setFluorideRealValue(fluorideReal);
            
            mockList.add(vo);
        }
        
        return mockList;
    }
    
    @Override
    public AlSafetyenvEnvIndicatorsVO getEnvIndicators(Integer year, Integer month, Integer day) {
        AlSafetyenvEnvIndicatorsVO vo = new AlSafetyenvEnvIndicatorsVO();
        
        // 默认使用当前日期
        LocalDate today = LocalDate.now();
        if (year == null) {
            year = today.getYear();
        }
        if (month == null) {
            month = today.getMonthValue();
        }
        if (day == null) {
            day = today.getDayOfMonth();
        }
        
        // 查询安全环保告警表中的排放数据，获取最新两条
        QueryWrapper<AlSafetyenvAlarm> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("year", year)
                   .eq("month", month)
                   .eq("day", day)
                   .orderByDesc("create_time")
                   .last("LIMIT 2");
        
        List<AlSafetyenvAlarm> alarmList = this.list(queryWrapper);
        
        if (alarmList != null && !alarmList.isEmpty()) {
            // 第一条：当前最新数据
            AlSafetyenvAlarm currentAlarm = alarmList.get(0);
            vo.setSo2YearlyEmission(currentAlarm.getSo2YearlyEmission());
            vo.setPmYearlyEmission(currentAlarm.getPmYearlyEmission());
            vo.setFluorideYearlyEmission(currentAlarm.getFluorideYearlyEmission());
            
            // 第二条：上一小时数据（如果存在）
            if (alarmList.size() > 1) {
                AlSafetyenvAlarm lastHourAlarm = alarmList.get(1);
                vo.setSo2YearlyEmissionLastHour(lastHourAlarm.getSo2YearlyEmission());
                vo.setPmYearlyEmissionLastHour(lastHourAlarm.getPmYearlyEmission());
                vo.setFluorideYearlyEmissionLastHour(lastHourAlarm.getFluorideYearlyEmission());
            }
        }
        
        return vo;
    }
    
    @Override
    public AluminumSafetyEnvVO getAluminumSafetyEnv(String orgCode) {
        AluminumSafetyEnvVO vo = new AluminumSafetyEnvVO();
        
        // 根据orgCode查询铝厂安全环保数据
        if (orgCode != null && !orgCode.isEmpty()) {
            // 查询该单位最新的环保监测数据
            QueryWrapper<AlSafetyenvAlarm> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("org_code", orgCode)
                       .orderByDesc("year", "month", "day")
                       .last("LIMIT 1");
            
            AlSafetyenvAlarm alarm = this.getOne(queryWrapper);
            
            if (alarm != null) {
                // 二氧化硫监测
                AluminumSafetyEnvVO.PollutionMonitor so2Monitor = new AluminumSafetyEnvVO.PollutionMonitor();
                so2Monitor.setPollutantName("二氧化硫");
                so2Monitor.setRealTimeValue(alarm.getSo2RealValue());
                so2Monitor.setHistoricalValue(alarm.getSo2StandardValue());
                vo.setSo2Monitor(so2Monitor);
                
                // 颗粒物监测
                AluminumSafetyEnvVO.PollutionMonitor pmMonitor = new AluminumSafetyEnvVO.PollutionMonitor();
                pmMonitor.setPollutantName("颗粒物");
                pmMonitor.setRealTimeValue(alarm.getPmRealValue());
                pmMonitor.setHistoricalValue(alarm.getPmStandardValue());
                vo.setPmMonitor(pmMonitor);
                
                // 氟化物监测（作为氮化物的替代）
                AluminumSafetyEnvVO.PollutionMonitor noxMonitor = new AluminumSafetyEnvVO.PollutionMonitor();
                noxMonitor.setPollutantName("氟化物");
                noxMonitor.setRealTimeValue(alarm.getFluorideRealValue());
                noxMonitor.setHistoricalValue(alarm.getFluorideStandardValue());
                vo.setNoxMonitor(noxMonitor);
            }
        }
        
        return vo;
    }

}
